from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from .jwt import decode_access_token

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/login")  # 用于 docs 中的“Authorize”按钮

def verify_token(token: str = Depends(oauth2_scheme)):
    payload = decode_access_token(token)
    if payload is None or payload.get("username") is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid or expired token",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return {"username": payload["username"]}
